﻿using CoreEx.Common.Logging;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;

namespace CoreEx.Common.Implementation.Logging
{
    /// <summary>
    /// A <see cref="IFactory{T}"/> implementation that allows 
    /// <see cref="ILogger"/> instances to be created by the <see cref="IServiceContainer"/>
    /// </summary>
    [Factory(typeof(ILogger))]
    public class LoggerFactory : IFactory<ILogger>
    {
        private readonly object _syncObject = new object();
        /// <summary>
        /// Creates a service instance using the given <see cref="T:LinFu.IoC.Interfaces.IFactoryRequest"/> instance.
        /// </summary>
        /// <param name="request">The <see cref="T:LinFu.IoC.Interfaces.IFactoryRequest"/> instance that describes the requested service.</param>
        /// <returns>
        /// An object instance that represents the service to be created. This cannot be <c>null</c>.
        /// </returns>
        public ILogger CreateInstance(IFactoryRequest request)
        {
            lock (_syncObject)
            {
                return CreateLogger(request);
            }
            
        }

        private static ILogger CreateLogger(IFactoryRequest request)
        {
            var actualFactory = request.Container.GetService<ILoggerFactory>();
            var logger = actualFactory.GetLogger(request.ServiceName);
            return logger;
        }
    }
}
